/*
 * Copyright 2020 lcnap
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pers.lcnap.springweb.example.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.lcnap.springweb.example.bean.User;
import pers.lcnap.springweb.example.mapper.UserMapper;

import java.util.List;

/**
 * 样例
 */
@Controller
public class AdminController {

    final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    public UserMapper userMapper;


    @GetMapping("/admin")
    public String admin(CsrfToken token, Model model) {
        logger.info(token.toString());
        logger.info(token.getToken());
        model.addAttribute("token", token.getToken());
        return "admin.html";
    }

    @GetMapping("/user")
    @ResponseBody
    @PreAuthorize("hasAuthority('ADMIN')")
    @Cacheable("user")
    public List<User> user(@AuthenticationPrincipal org.springframework.security.core.userdetails.User user) {
        logger.info("called user().");
        logger.info(user.toString());
        return userMapper.selectList(null);

    }

    @GetMapping("/userdetails")
    @ResponseBody
    public UserDetails userDetails(@AuthenticationPrincipal UserDetails userDetails) {
        return userDetails;
    }
}
